<template>
  <section class="todoapp">
    <hm-header @add-event="handleAdd"></hm-header>
    <hm-main :list="showList" 
    @del-event="handleDel" 
    @change-done-event="changeDone"
    @check-all="checkAll"
    ></hm-main>
    <hm-footer :list="list" 
    :state="state" 
    @del-all="delAll" 
    @show-list="state=$event"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  '#/': 'all',
  '#/active': 'doing',
  '#/completed': 'do'
}
import HmHeader from './components/hm-header.vue'
import HmMain from './components/hm-main.vue'
import HmFooter from './components/hm-footer.vue'
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter
  },
  data() {
    return {
      list: JSON.parse(window.localStorage.getItem('list')) || [],
      state: obj[location.hash] || 'all'
    }
  },
  methods: {
    handleDel(id) {
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index,1)
    },
    changeDone(id) {
      const index = this.list.findIndex(item => item.id === id)
      this.list[index].done = !this.list[index].done
    },
    handleAdd(value) {
      const id = this.list.length ? this.list.slice(-1)[0].id+1 : 1
      const obj = {
        id,
        name: value,
        done: false
      }
      this.list.push(obj)
    },
    checkAll(value) {
      this.list.forEach(item => {
        item.done = value
      })
    },
    delAll() {
      this.list = this.list.filter(item => item.done === false)
    },
    
  },
  computed: {
    showList() {
      if(this.state === 'all') {
        return this.list
      } else if (this.state === 'doing') {
        return this.list.filter(item => item.done === false)
      } else {
        return this.list.filter(item => item.done === true)
      }
    }
  },
  watch: {
    list: {
      handler(newVal) {
        window.localStorage.setItem('list',JSON.stringify(newVal))
      },
      deep:true
    }
  }
}
</script>

<style></style>
